{% extends "base.html" %}

{% block title %}{{ post.title }} - SteHub{% endblock %}

{% block content %}
<div class="row">
    <!-- 帖子内容 -->
    <div class="col-lg-9">
        <!-- 帖子头部 -->
        <div class="card mb-4">
            <div class="card-body">
                <!-- 导航面包屑 -->
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb">
                        <li class="breadcrumb-item"><a href="{{ url_for('forum.posts') }}">论坛</a></li>
                        <li class="breadcrumb-item"><a href="{{ url_for('forum.view_category', category_id=post.category.id) }}">{{ post.category.name }}</a></li>
                        <li class="breadcrumb-item active">{{ post.title|truncate(30) }}</li>
                    </ol>
                </nav>

                <!-- 帖子标题和信息 -->
                <h1 class="h3 mb-3">{{ post.title }}</h1>
                
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <div class="d-flex align-items-center">
                        <img src="{{ post.author.avatar_url or url_for('static', filename='images/default-avatar.png') }}" 
                             class="rounded-circle me-2" width="32" height="32" alt="头像">
                        <div>
                            <a href="#" class="text-decoration-none">{{ post.author.username }}</a>
                            <div class="text-muted small">
                                {{ post.created_at|format_timestamp }}
                                {% if post.updated_at != post.created_at %}
                                · 编辑于 {{ post.updated_at|relative_time }}
                                {% endif %}
                            </div>
                        </div>
                    </div>
                    
                    <div class="d-flex align-items-center">
                        <span class="badge me-2" style="background-color: {{ post.category.color }};">
                            {{ post.category.name }}
                        </span>
                        {% if post.is_sticky %}
                        <span class="badge bg-warning me-2">置顶</span>
                        {% endif %}
                        {% if post.is_featured %}
                        <span class="badge bg-danger me-2">精华</span>
                        {% endif %}
                    </div>
                </div>

                <!-- 帖子内容 -->
                <div class="post-content mb-4">
                    {{ post.content|safe }}
                </div>

                <!-- 帖子操作 -->
                <div class="d-flex justify-content-between align-items-center">
                    <div class="d-flex align-items-center">
                        <!-- 点赞按钮 -->
                        <button class="btn btn-outline-danger btn-sm me-2 like-btn" 
                                data-post-id="{{ post.id }}"
                                {% if not current_user.is_authenticated %}disabled{% endif %}>
                            <i class="fas fa-heart {% if user_liked %}text-danger{% endif %}"></i>
                            <span class="like-count">{{ post.like_count }}</span>
                        </button>

                        <span class="text-muted me-3">
                            <i class="fas fa-eye me-1"></i>{{ post.view_count }}
                        </span>
                    </div>

                    <div class="d-flex align-items-center">
                        {% if current_user.is_authenticated and (current_user.id == post.author_id or current_user.is_admin) %}
                        <a href="{{ url_for('forum.edit_post', post_id=post.id) }}" class="btn btn-outline-primary btn-sm me-2">
                            <i class="fas fa-edit me-1"></i>编辑
                        </a>
                        <button class="btn btn-outline-danger btn-sm delete-post-btn" data-post-id="{{ post.id }}">
                            <i class="fas fa-trash me-1"></i>删除
                        </button>
                        {% endif %}
                    </div>
                </div>
            </div>
        </div>

        <!-- 评论区域 -->
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="fas fa-comments me-2"></i>评论
                    <span class="badge bg-primary">{{ post.comment_count }}</span>
                </h5>
            </div>

            <!-- 评论列表 -->
            <div class="card-body">
                {% if comments %}
                    {% for comment in comments %}
                    <div class="comment-item mb-4 pb-3 border-bottom" id="comment-{{ comment.id }}">
                        <div class="d-flex">
                            <img src="{{ comment.author.avatar_url or url_for('static', filename='images/default-avatar.png') }}" 
                                 class="rounded-circle me-3" width="40" height="40" alt="头像">
                            <div class="flex-grow-1">
                                <div class="d-flex justify-content-between align-items-start mb-2">
                                    <div>
                                        <strong>{{ comment.author.username }}</strong>
                                        <span class="text-muted small ms-2">{{ comment.created_at|relative_time }}</span>
                                    </div>
                                    {% if current_user.is_authenticated and (current_user.id == comment.author_id or current_user.is_admin) %}
                                    <button class="btn btn-sm btn-outline-danger delete-comment-btn" 
                                            data-comment-id="{{ comment.id }}">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                    {% endif %}
                                </div>
                                <div class="comment-content">
                                    {{ comment.content|safe }}
                                </div>
                            </div>
                        </div>
                    </div>
                    {% endfor %}
                {% else %}
                    <div class="text-center py-4">
                        <i class="fas fa-comment-slash fa-2x text-muted mb-3"></i>
                        <p class="text-muted">暂无评论，快来发表第一条评论吧！</p>
                    </div>
                {% endif %}
            </div>

            <!-- 发表评论 -->
            {% if current_user.is_authenticated %}
            <div class="card-footer">
                <form id="commentForm" method="POST" action="{{ url_for('forum.add_comment', post_id=post.id) }}">
                    <div class="mb-3">
                        <label for="commentContent" class="form-label">发表评论</label>
                        <textarea class="form-control" id="commentContent" name="content" 
                                  rows="3" placeholder="请输入评论内容..." required maxlength="1000"></textarea>
                        <div class="form-text">支持 Markdown 语法，最多1000个字符</div>
                    </div>
                    <div class="d-flex justify-content-end">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-paper-plane me-2"></i>发表评论
                        </button>
                    </div>
                </form>
            </div>
            {% else %}
            <div class="card-footer text-center">
                <p class="mb-0">
                    <a href="{{ url_for('auth.login') }}" class="text-decoration-none">登录</a>
                    后即可发表评论
                </p>
            </div>
            {% endif %}
        </div>
    </div>

    <!-- 右侧边栏 -->
    <div class="col-lg-3">
        <!-- 作者信息 -->
        <div class="card mb-4">
            <div class="card-header">
                <h6 class="mb-0"><i class="fas fa-user me-2"></i>作者信息</h6>
            </div>
            <div class="card-body text-center">
                <img src="{{ post.author.avatar_url or url_for('static', filename='images/default-avatar.png') }}" 
                     class="rounded-circle mb-3" width="80" height="80" alt="头像">
                <h6>{{ post.author.username }}</h6>
                {% if post.author.bio %}
                <p class="small text-muted">{{ post.author.bio }}</p>
                {% endif %}
                <div class="small text-muted">
                    <div>注册时间: {{ post.author.created_at|relative_time }}</div>
                    <div>帖子数: {{ post.author.posts|length }}</div>
                </div>
                {% if current_user.is_authenticated and current_user.id != post.author.id %}
                <a href="{{ url_for('chat.private_chat', user_id=post.author.id) }}" 
                   class="btn btn-outline-primary btn-sm mt-2">
                    <i class="fas fa-comment me-1"></i>发送私信
                </a>
                {% endif %}
            </div>
        </div>

        <!-- 相关帖子 -->
        <div class="card">
            <div class="card-header">
                <h6 class="mb-0"><i class="fas fa-link me-2"></i>相关帖子</h6>
            </div>
            <div class="list-group list-group-flush">
                <!-- 这里可以显示同分类的其他帖子 -->
                <a href="#" class="list-group-item list-group-item-action small">同分类的其他帖子...</a>
                <a href="#" class="list-group-item list-group-item-action small">热门讨论...</a>
                <a href="#" class="list-group-item list-group-item-action small">最新发布...</a>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    // 点赞功能
    const likeBtn = document.querySelector('.like-btn');
    if (likeBtn) {
        likeBtn.addEventListener('click', function() {
            const postId = this.dataset.postId;
            const likeCount = this.querySelector('.like-count');
            const heartIcon = this.querySelector('.fa-heart');
            
            fetch(`/forum/post/${postId}/like`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    likeCount.textContent = data.like_count;
                    if (data.action === 'like') {
                        heartIcon.classList.add('text-danger');
                    } else {
                        heartIcon.classList.remove('text-danger');
                    }
                }
            })
            .catch(error => {
                console.error('Error:', error);
            });
        });
    }

    // 删除帖子
    const deletePostBtn = document.querySelector('.delete-post-btn');
    if (deletePostBtn) {
        deletePostBtn.addEventListener('click', function() {
            const postId = this.dataset.postId;
            
            if (confirm('确定要删除这个帖子吗？此操作不可恢复。')) {
                fetch(`/forum/post/${postId}/delete`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        window.location.href = data.redirect_url;
                    } else {
                        alert('删除失败: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('删除失败');
                });
            }
        });
    }

    // 删除评论
    const deleteCommentBtns = document.querySelectorAll('.delete-comment-btn');
    deleteCommentBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            const commentId = this.dataset.commentId;
            
            if (confirm('确定要删除这条评论吗？')) {
                fetch(`/forum/comment/${commentId}/delete`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        document.getElementById(`comment-${commentId}`).remove();
                    } else {
                        alert('删除失败: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('删除失败');
                });
            }
        });
    });

    // 评论表单提交
    const commentForm = document.getElementById('commentForm');
    if (commentForm) {
        commentForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            
            fetch(this.action, {
                method: 'POST',
                body: formData,
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 清空表单
                    this.reset();
                    // 重新加载页面以显示新评论
                    location.reload();
                } else {
                    alert('评论失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('评论失败');
            });
        });
    }
});
</script>
{% endblock %}